<template>
  <view class="p-1" :style="{
    background: bgColor
  }">
    <view
      :style="{ borderRadius: item.borderRadius || '8px' }"
      v-for="(item, index) in cellConfig"
      :key="index"
    >
      <view class="flex-col mx-2 pt-3 font-bold" v-if="item.title">
        <text>{{ item.title }}</text>
        <u-line margin="0.5em 0" />
      </view>
      <u-cell-group
        :customStyle="{ marginBottom: '6px' }"
        v-if="item.children && item.children.length > 0"
        class="mt-1"
        :border="false"
      >
        <view v-for="(child, cindex) in item.children" :key="cindex">
          <view v-if="child.type == 'txt-double'" class="p-2 px-4 flex">
            <view v-for="(textd, tdIndex) in child.title" :key="tdIndex" class="flex-1">
              <text class="text-slate-400 text-sm mr-2"> {{ textd }} </text>
              <text class="text-sm">{{ child.value[tdIndex] }}</text>
            </view>
            <view> </view>
          </view>
          <view v-else-if="child.type == 'img'" class="box-border p-2 px-4 flex w-full justify-center items-center">
            <u-image radius="5px" :src="child.value" mode="aspectFill" :width="child.style?.width || '180rpx'" :height="child.style?.height || '180rpx'"></u-image>
          </view>
          <u-cell v-else :border="false">
            <u-icon slot="icon" :name="child.prefixIcon"></u-icon>
            <u-icon slot="right-icon" :name="child.suffixIcon"></u-icon>
            <view slot="title" class="whitespace-nowrap mr-2 min-w-16 text-sm text-gray-400">{{ child.title }}</view>
            <view slot="value" class="text-gray-900 text-sm">
              <text>{{ child.value }}</text>
            </view>
          </u-cell>
          <u-line v-if="child.border" margin="0.5em 0" />
        </view>
      </u-cell-group>
      <u-cell v-else>
        <view slot="title" class="whitespace-nowrap mr-2 text-sm text-gray-400">{{ item.title }}</view>
        <view slot="value" class="text-gray-900 text-sm">{{ item.value }}</view>
      </u-cell>
      <u-line v-if="item.border" margin="0.5em 0" />
    </view>
  </view>
</template>

<script>

/**
 * 时间关系,未写组件文档,如有疑问请联系 @fmy
 */
export default {
  props: {
    info: {
      type: Object,
      default: () => ({}),
    },
    config: {
      type: Array,
      default: () => [],
    },
    dictsData: {
      type: Object,
      default: () => ({}),
    },
    bgColor: {
      type: String,
      default: "#fff",
    },
  },
  components: {},
  data() {
    return {
      dicts: {},
      cellConfig: [],
    };
  },
  computed: {},
  methods: {
    /**
     * 递归查找更新相应值
     * cellConfig 配置项
     * updates 数据源
     * defaultValue 为空时默认值
     */
    updateValues(cellConfig, updates, defaultValue = "") {
      // console.log(">> updateValue ", { cellConfig, updates, defaultValue });
      const that = this;

      // 递归函数来更新值
      function updateNode(node, updates) {
        if (node.hasOwnProperty("key") /* && updates.hasOwnProperty(node.key) */) {
          if (Array.isArray(node.key)) {
            // console.log("node.key", node);
            for (let i in node.key) {
              // 多行文本
              if (!Array.isArray(node.value)) node.value = [];

              // 如果该字段是字典值
              // console.log("如果该字段是字典值", node.dict,  Array.isArray(node.dict), (node.dict[i] != null || node.dict[i] !== undefined) )
              if (node.dict && Array.isArray(node.dict) && node.dict[i] != null && node.dict[i] !== undefined) {
                node.value[i] = getDictLabel(node.dict[i], updates[node.key[i]]) || defaultValue;
              } else {
                // 设置值 如果找不到对应的值，则使用默认值
                node.value[i] = updates[node.key[i]] ?? defaultValue;
              }

              // 如果设置了自定义格式化
              if (node.formatter) {
                node.value[i] = node.formatter(node.key[i], node.value[i]);
              }
            }
          } else {
            if (node.dict && node.dict != null && node.dict !== undefined) {
              node.value = getDictLabel(node.dict, updates[node.key]) ?? defaultValue;
            } else {
              // 设置值 如果找不到对应的值，则使用默认值
              node.value = updates[node.key] ?? defaultValue;
            }
            // 如果设置了自定义格式化
            if (node.formatter) {
              node.value = node.formatter(node.key, node.value);
            }
          }
        }
        if (Array.isArray(node.children)) {
          node.children.forEach((child) => updateNode(child, updates));
        }
      }

      // 遍历 cellConfig 的顶层节点
      cellConfig.forEach((node) => {
        updateNode(node, updates);
      });

      // 强制刷新
      this.$forceUpdate();

      this.cellConfig = cellConfig;

      /**
       * 获取系统字典/业务字典 并返回正确的lable
       * @param {*} dictName
       * @param {*} value
       * @param {*} dictType [system,business]
       */
      function getDictLabel(dictName, value /* , dictType = "system" */) {
        const dict = that.dicts[dictName];
        return dict?.find((v) => v.dictValue == value)?.dictLabel || value;

        // 不在这里请求数据，而是直接取 this.dicts （去除 async 网络等待，会在设置数据时出现某些问题🫠
        // try {
        //   const reqType =
        //     dictType === "system" ? getSysDictByName : getBizDictByName;
        //   const { data } = await reqType(dictName);
        //   // console.log("data?.find((v) => v.dictValue == value)", data?.find((v) => v.dictValue == value).dictLabel)
        //   return data?.find((v) => v.dictValue == value)?.dictLabel || value;
        // } catch (error) {
        //   console.error("查找字典失败：", error);
        //   return value;
        // }
      }
    },

    // 设置字典
    setDict(data) {
      this.dicts = data;
    },
  },
  watch: {
    dictsData: {
      handler(newval) {
        this.dicts = newval;
      },
    },
    config: {
      handler(newval) {
        this.cellConfig = newval;
      },
      // deep: true,
    },
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() {},
};
</script>

<style lang="scss" scoped></style>
